package madrid.mae.app;

import mae.app.R;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MadridAmberPiece extends Activity {

	private MadridAmberHelper dbMadridAmberHelper = null;
	private Cursor myCursor = null;
	private MadridAmberAdapter adapter = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.piece);

			ListView myListView = (ListView) findViewById(R.id.list);

			dbMadridAmberHelper = new MadridAmberHelper(this, null, null, 0);

			dbMadridAmberHelper.createDatabase();

			dbMadridAmberHelper.openDatabase();

			myCursor = dbMadridAmberHelper.getCursor();

			startManagingCursor(myCursor);

			adapter = new MadridAmberAdapter(myCursor);

			myListView.setAdapter(adapter);
		} catch (Exception e) {
			Log.e("ERROR", "ERROR IN CODE: " + e.toString());
			e.printStackTrace();
		}
	}

	class MadridAmberAdapter extends CursorAdapter {
		MadridAmberAdapter(Cursor c) {
			super(MadridAmberPiece.this, c);
		}

		@Override
		public void bindView(View row, Context context, Cursor c) {
			MadridAmberHolder holder = (MadridAmberHolder) row.getTag();
			holder.populateFrom(c, dbMadridAmberHelper);
		}

		@Override
		public View newView(Context context, Cursor c, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.row, parent, false);
			MadridAmberHolder holder = new MadridAmberHolder(row);
			row.setTag(holder);
			return (row);
		}
	}

	static class MadridAmberHolder {
		private TextView piece = null;
		private TextView value = null;
		private EditText quanity = null;

		MadridAmberHolder(View row) {
			piece = (TextView) row.findViewById(R.id.pieceText);
			value = (TextView) row.findViewById(R.id.valueText);
			quanity = (EditText) row.findViewById(R.id.quanityText);
		}

		void populateFrom(Cursor c, MadridAmberHelper r) {
			piece.setText(r.getPiece(c));
			value.setText(r.getValue(c));
			quanity.setText(r.getQuanity(c));
		}
	}
}
